package com.feng.main;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

public class HtmlContent {
	
	
	
	/**
	 * 获取HttpEntity
	 * @return HttpEntity网页实体
	 */
	private HttpEntity getHttpEntity(String url){
		
		HttpResponse response = null;//创建请求响应
		
		//创建httpclient对象
		HttpClient httpClient = HttpClients.createDefault();
		
		HttpGet get = new HttpGet(url);
		
		RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(5000)	//设置请求超时时间
				.setConnectionRequestTimeout(5000)		//设置传输超时时间
				.build();
		
		get.setConfig(requestConfig);//设置请求的参数
		
		//
		try {
			response = httpClient.execute(get);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//获取返回状态 200为响应成功
//		StatusLine state = response.getStatusLine();
		
		//获取网页实体
		HttpEntity httpEntity = response.getEntity();
		
		return httpEntity;
//		try {
//			return httpEntity.getContent();
//		} catch (IllegalStateException | IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return null;
	}
	

	
	
	
	/**
	 * 获取整个html以String形式输出
	 * @param url
	 * @return
	 */
	public String getContent(String url){
		
		HttpEntity httpEntity = getHttpEntity(url);
		String content = "";
		try {
			
			InputStream is = httpEntity.getContent();
			
			InputStreamReader isr = new InputStreamReader(is);
			
			char[] c = new char[1024];
			int l = 0;
			
			while((l = isr.read(c)) != -1){
				content += new String(c,0,l);
			}
			
			isr.close();
			is.close();
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return content;
	}
	
}
